package com.dongdongshop.service.impl;

import cn.hutool.core.util.StrUtil;
import com.dongdongshop.domain.rep.ItemCatReq;
import com.dongdongshop.domain.res.ItemCatRes;
import com.dongdongshop.mapper.ItemMapper;
import com.dongdongshop.model.ItemCat;
import com.dongdongshop.service.ItemService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class ItemServiceImpl implements ItemService {
    @Autowired
    private ItemMapper itemMapper;


    /**
     * 商品类目查询
     * @return
     */
    @Override
    public List<ItemCatRes> queryTree() {
        List<ItemCat> catList=itemMapper.queryTree();
        List<ItemCatRes> catResList=getTrzz(catList,0L);
        return catResList;
    }



    /**
     * 商品类目增加修改操作
     * @param itemCatReq
     * @return
     */
    @Override
    public void save(ItemCatReq itemCatReq) {
        if (itemCatReq.getParentId()!=null){
            itemMapper.add(itemCatReq);
        }else {
            itemMapper.update(itemCatReq);
        }
    }


    /**
     * 商品类目删除操作
     * @param id
     * @return
     */
    @Override
    public void delete(Long id) {
        itemMapper.delete(id);
    }

    @Override
    public List<ItemCatRes> queryAll() {
        List<ItemCat> catList=itemMapper.queryAll();
        List<ItemCatRes> collect = catList.stream().map(i -> {
            ItemCatRes itemCatRes = new ItemCatRes();
            BeanUtils.copyProperties(i, itemCatRes);
            return itemCatRes;
        }).collect(Collectors.toList());
        return collect;
    }


    private List<ItemCatRes> getTrzz(List<ItemCat> catList, Long pid) {
        List<ItemCatRes> catResList=new ArrayList<ItemCatRes>();
        for (ItemCat itemCat : catList) {
            if (Objects.equals(pid,itemCat.getParentId())){
                ItemCatRes itemCatRes=new ItemCatRes();
                itemCatRes.setId(itemCat.getId());
                itemCatRes.setName(itemCat.getName());
                itemCatRes.setTypeId(itemCat.getTypeId());
                itemCatRes.setChildren(getTrzz(catList,itemCat.getId()));
                catResList.add(itemCatRes);
                if (itemCatRes.getChildren().size()==0){
                    itemCatRes.setChildren(null);
                }
            }
        }
        return catResList;
    }
}
